package com.naiterui.ehp.bs.patient.service.impl;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.naiterui.ehp.bs.patient.bo.notice.BaseNotice;
import com.naiterui.ehp.bs.patient.config.TemplateConfig;
import com.naiterui.ehp.bs.patient.config.TemplateProperties;
import com.naiterui.ehp.bs.patient.service.ITemplateNoticeService;
import com.naiterui.ehp.bs.wechat.service.ITemplateMsgApiService;

/**
 * @author zhoupeipei
 * @date 2019-06-19 15:07
 * @since 1.0.0
 */
@Service
public class ApTemplateNoticeServiceImpl implements ITemplateNoticeService {
    private static final Logger LOGGER = LoggerFactory.getLogger(ApTemplateNoticeServiceImpl.class);
    @Autowired
    ITemplateMsgApiService templateMsgApiService;
    @Autowired
    TemplateConfig templateConfig;

    @Override
    public void notice(BaseNotice param) {
        if (null == param || !param.validate()) {
            LOGGER.error("模板消息发送失败，参数错误，模板信息{}", param);
            return;
        }
        //通过label查询模板配置，来获取微信的templateId以及基础文案
        TemplateProperties templateProperties = Optional.ofNullable(param.getTemplateLabel())
                                                        .map(label -> templateConfig.templateMap().get(label)).get();

        if (null == templateProperties) {
            LOGGER.info("模板配置信息不全，请添加配置到template.yml，配置{}", templateProperties);
            return;
        }

        //处理模板内容
        List<TemplateProperties.Content> contentList = templateProperties.cloneContent();

        //文本色号
        Map<String, String> colorMap = contentList.stream().collect(Collectors.toMap(TemplateProperties.Content::getKey,
                TemplateProperties.Content::getColor));
        // 格式化处理文本内容
        param.handleContent(contentList);
        Map<String, Object> dataMap = contentList.stream()
                                                 .collect(Collectors.toMap(TemplateProperties.Content::getKey, TemplateProperties.Content::getValue));

        templateMsgApiService.sendTemplateToUrl(param.getOpenId(), templateProperties.getTemplateId(), param.getTargetPage(), dataMap, colorMap);
    }
}
